package object;

import utils.SHA1;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Blob extends BaseObject<Blob> implements Serializable{

    public Blob(File file) throws Exception{
        this.fmt = "Blob";
        this.mode = "100644";
        this.name = file.getName();
        this.path = file.getPath();
        this.key = SHA1.getHash(file);
        this.content = genContent(file);

        writeObject();
    }

    @Override
    public void writeObject() {
        try {

            ObjectOutputStream out =
                    new ObjectOutputStream(new FileOutputStream(".jit" + File.separator + "objects" + File.separator + this.key));
            out.writeObject(this);
            out.close();
        }
        catch(Exception ex){
            ex.printStackTrace();
        }

    }

    public static Blob deserialize(String Id) throws Exception {
        try{
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(".jit" + File.separator + "objects" +File.separator + Id));
            return (Blob) in.readObject();
        }
        catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    public String genContent(File file) throws IOException{
        String value = "";

        try {
            Path targetFilePath = Paths.get(file.getAbsolutePath());
            value = Files.readString(targetFilePath);
        } catch (IOException ex) {
            ex.getStackTrace();
        }
        return value;
    }
}
